<template>
  <div class="fr page">
      <button :class="{ disabled: page == 1 }" :disabled="page == 1" @click="$emit('pageChange', page - 1)">上一页</button>
      <!-- 首页 -->
       <button
        v-if="pageStartAndEnd.start > 1"
        @click="$emit('pageChange', 1)"
        >{{1}}</button>
         <!-- 更多页 -->
      <button v-if="pageStartAndEnd.start > 2">...</button>
      <template v-for="index in pageStartAndEnd.end">
        <button
        :class="{ active: index === page }"
        :key="index"
        v-if="index >= pageStartAndEnd.start"
        @click="$emit('pageChange', index)"
        >{{index}}</button>
      </template>
      <!-- 更多页 -->
      <button v-if="pageStartAndEnd.end < totalPage - 1">...</button>
      <!-- 尾页 -->
       <button
        v-if="pageStartAndEnd.end < totalPage"
        @click="$emit('pageChange', totalPage)"
        >{{totalPage}}</button>
        <!-- 最后一页禁止跳转 -->
      <button :class="{ disabled: page == totalPage }" :disabled="page == totalPage" @click="$emit('pageChange', page + 1)">下一页</button>
      <button class="total">{{total}}条</button>
    </div>
</template>

<script>
export default {
  name: 'Paginatuion',
  props: {
    // 总数量
    total: Number,
    // 每页数量
    pageSize: Number,
    // 当前页码
    page: Number
  },
  computed: {
    // 计算总页数 = 总数量 / 每页数量
    totalPage () {
      return Math.ceil(this.total / this.pageSize)
    },
    // 一次性只显示5页 低于5页 显示总页数
    // 计算开始页码 - 结束页码
    pageStartAndEnd () {
      // 1.定义开始，结束页码
      let start = 0
      let end = 0
      // 2.判断总页数 低于5页
      if (this.totalPage <= 5) {
        start = 0
        end = this.totalPage
      } else {
        // 设置开始页
        start = this.page - 2
        // 设置结束页
        end = this.page + 2
        // 处理边界值 -> 起步不能低于1
        if (start <= 1) {
          start = 1; end = 5
        }
        // 处理边界值 -> 结束不能高于最大页
        if (end >= this.totalPage) {
          start = this.totalPage - 4; end = this.totalPage
        }
      }
      return { start, end }
    }

  }
}
</script>

<style lang="scss" scoped>
.page {
  width: 733px;
  height: 66px;
  overflow: hidden;
  margin: 0 auto;
  display: flex;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 25.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;
  &.active{
    cursor: not-allowed;
    background-color: #409eff;
    color: #fff;
  }
  &.disable {
    color: #c0c4cc;
    cursor: not-allowed;
  }
  &.total{
    margin-left: 20px;
  }
  }
}
</style>
